#include <linux/init.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/kthread.h>

static struct task_struct *my_thread;

// 线程函数
static int my_thread_fn(void *data)
{
    while (!kthread_should_stop()) {
        printk(KERN_INFO "Thread is running...\n");
        msleep(1000);  // 等待 1 秒
    }
    printk(KERN_INFO "Thread is stopping...\n");
    return 0;
}

static int __init my_module_init(void)
{
    // 创建内核线程
    my_thread = kthread_create(my_thread_fn, NULL, "my_thread");
    if (IS_ERR(my_thread)) {
        printk(KERN_ERR "Failed to create kernel thread.\n");
        return PTR_ERR(my_thread);
    }

    // 启动线程
    wake_up_process(my_thread);

    printk(KERN_INFO "Kernel thread created.\n");
    return 0;
}

static void __exit my_module_exit(void)
{
    // 停止线程
    if (my_thread) {
        int ret = kthread_stop(my_thread);
        printk(KERN_INFO "Kernel thread stopped with return code: %d\n", ret);
    }
}

module_init(my_module_init);
module_exit(my_module_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple module to demonstrate msleep.");

